import React, { useState, useMemo, useEffect } from 'react';
import { useTimer, Ret, obj_str, CurTip, PanelFind, filter_row, useCmd, useHigh, is_empty, loc, GridTable } from 'sui';
import { get_cur_main } from '../cmd/base';
import { load_real } from '../cmd/real';
import { tree_col, expand_sub} from '../cmd/tree';

let g_block = true;

const RealView = ({ plc, main, hreturn }) => {
    const [row, setRow] = useState();
    const [real, setReal] = useState();
    const umd = useCmd(null, "plc");
    const [high] = useHigh(140, 100);

    useEffect(() => {
        get_cur_main(main, r => expand_sub(main, r, v => {
            setRow(v);
            g_block = false;
        }));
    }, [main]);

    const filterRow = useMemo(() => {
        const lst = ["m", "k"];

        if (is_empty(row)) {
            return null;
        }

        const ret =  filter_row(row, lst, umd.filter);

        ret.forEach(d => {
            const m = obj_str(d, "m");
            const v = obj_str(real, m);

            if (d.value !== v) {
                d["value"] = v;
            }
        });

        return ret;
    }, [umd.filter, row, real]);

    const reducer = (state, action) => {
        if (is_empty(main)) {
            return;
        }

        if (g_block) {
            return;
        }

        g_block = true;

        load_real(main, (v) => {
            if (v) {
                setReal(v)
            }

            g_block = false;
        });

        return state;
    }

    useTimer(reducer, 500);

    const col = [
        {name: loc("mbq"), key: 'm', width: 400, formatter: props => tree_col(props.row, null)},
        {name: loc("zw_19"), key: 'k', width: 200},
        {name: loc("lx"), key: 'ltp', width: 140},
        {name: loc("cmd_60"), key: 'value', width: 200},
    ];

    const Left = () => <CurTip label={obj_str(plc, "name")} cur={loc("mg_162")}>{obj_str(main, "name")}</CurTip>;

    const Right = () => <Ret hcmd={() => hreturn()}/>;

    return (
        <div className="ml-8">
            <PanelFind left={<Left/>} right={<Right/>} cl="gray" hcmd={v => umd.setFilter(v)}/>
            <GridTable col={col} row={filterRow} high={high}/>
        </div>
    );
};

export {RealView};
